package com.ple.app.suggest;

import android.app.AlertDialog;
import android.app.DatePickerDialog;
import android.content.ContentValues;
import android.content.DialogInterface;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.view.LayoutInflater;
import android.view.MotionEvent;
import android.view.View;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.Button;
import android.widget.DatePicker;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.PopupWindow;
import android.widget.SimpleAdapter;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.ple.app.importdata.InputSeed_Activity;
import com.ple.app.importdata.MyopenHelper;
import com.ple.app.jzsf.R;
import com.ple.app.map.ChooseAreaActivity;
import com.ple.app.sevlet.GetFromServer;
import com.ple.app.sevlet.GetIdList;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


public class Gsetsuggest_Activity extends Activity {

    private ImageButton get_data;
    private EditText data;
    private DatePickerDialog datePickerDialog;
    private EditText choose_dk;
    private EditText choose_grown;//栽培
    private EditText choose_manure;//肥料
    private Spinner fertilizer;
    private Spinner decision_type;
    private String fertilizer_value;
    private String decision_value;
   private ListView listView;
    private Button get_decision;
    private String[] list_content={"ID","dk","grown","data","fertilizer","manure","decisiontype"};
    private  int[] image=new int[]{R.drawable.fa1,R.drawable.fa2,R.drawable.fa3};
    private int operation_id;
    private int i;//图标索引
    private TextView option;
    private String manure_id="0";//test
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_gsetsuggest);
        listView= (ListView) findViewById(R.id.decision);
        initData();
        /**
         * listview事件
         */
       //listView= (ListView) findViewById(R.id.decision);
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            }
        });

        /**
         *  选中状态List view的Item
         */
        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                //HashMap<String,String> getmap= (HashMap<String, String>) listView.getItemAtPosition(position);
                //String ID=getmap.get("ID");
                Intent intent=new Intent(Gsetsuggest_Activity.this,Display_decisionActivity.class);
                startActivity(intent);

            }
        });
        listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
                HashMap<String,String> getmap= (HashMap<String, String>) listView.getItemAtPosition(position);
                String ID=getmap.get("ID");
                operation_id=Integer.valueOf(ID);
                showPopupWindow(view);
                return true;//想长按时不执行单机事件，则设置为true；
            }
        });
        /**
         * listview事件结束
         */
        /**
         * 选择地块
         */
        choose_dk= (EditText) findViewById(R.id.choose_dk);
        choose_dk.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Gsetsuggest_Activity.this,ChooseAreaActivity.class);
                startActivity(intent);
            }
        });
        /**
         * 选择栽培信息
         */
        choose_grown= (EditText) findViewById(R.id.choose_grown);
        choose_grown.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(Gsetsuggest_Activity.this,getcultivateActivity.class);
                // startActivity(intent);
                startActivityForResult(intent,0);
            }
        });
        /**
         * 获得施肥类型
         */
        fertilizer= (Spinner) findViewById(R.id.fertilizer);
        fertilizer.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                fertilizer_value=fertilizer.getSelectedItem().toString();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        /**
         * 选择肥料信息
         */
        choose_manure= (EditText) findViewById(R.id.manure_brand);
        choose_manure.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent=new Intent(Gsetsuggest_Activity.this,ManureActivity.class);
                // startActivity(intent);
                startActivityForResult(intent,1);
            }
        });
        /**
         * 选择决策类型
         */
        decision_type= (Spinner) findViewById(R.id.decision_type);
        decision_type.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                decision_value=decision_type.getSelectedItem().toString();
               //i=position;
            }
            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });

        /**
         * 选择时间
         */
        get_data = (ImageButton) findViewById(R.id.get_data);
        data = (EditText) findViewById(R.id.data);
        get_data.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Calendar calendar=Calendar.getInstance();
                datePickerDialog=new DatePickerDialog(Gsetsuggest_Activity.this, new DatePickerDialog.OnDateSetListener() {
                    @Override
                    public void onDateSet(DatePicker view, int year, int month, int dayOfMonth) {
                        int month1=month+1;
                        String data_text = year + "-" + month1+ "-" + dayOfMonth;
                        data.setText(data_text);
                    }
                },calendar.get(Calendar.YEAR),calendar.get(Calendar.MONTH),calendar.get(Calendar.DAY_OF_MONTH));
                datePickerDialog.show();
            }
        });
        /**
         * 获得决策方案
         */
        get_decision= (Button) findViewById(R.id.get_decision);
        get_decision.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //需加判断
                if(manure_id.equals("0"))Toast.makeText(getApplicationContext(),"请选择肥料",Toast.LENGTH_LONG).show();
                else{
               // servlet(manure_id);
                getdecision();
                updatalistview();
                Toast.makeText(getApplicationContext(),"已获得决策方案",Toast.LENGTH_LONG).show();}
            }
        });
    }//oncreat

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        //super.onActivityResult(requestCode, resultCode, data);
        if(data!=null){
            if(requestCode==0&&resultCode==0){
                Bundle bundle=data.getExtras();
                String name=bundle.getString("name");
                choose_grown.setText(name);
                choose_grown.setTextColor(getResources().getColor(R.color.black));
            }
            if(requestCode==1&&resultCode==1){
                Bundle bundle=data.getExtras();
                String name=bundle.getString("name");
                String ID=bundle.getString("ID");
                manure_id=ID;
                choose_manure.setText(name);
                choose_manure.setTextColor(getResources().getColor(R.color.black));
            }
        }
        else{return;}
    }

    /**
     * 自定义方法
     */
    private void initData() {
        String year1, month1, data1;
        data = (EditText) findViewById(R.id.data);
        Calendar calendar = Calendar.getInstance();
        year1 = String.valueOf(calendar.get(Calendar.YEAR));
        int a=calendar.get(Calendar.MONTH)+1;
        month1 = String.valueOf(a);
        data1 = String.valueOf(calendar.get(Calendar.DATE));
        String data_text = year1 + "-" + month1 + "-" + data1;
        data.setText(data_text);
        option= (TextView) findViewById(R.id.option);
        updatalistview();
    }

    /**
     * 添加获得方案
     */
    private void getdecision()  {
         i=decision_type.getSelectedItemPosition();
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        MyopenHelper myopenhelper=new MyopenHelper(this,"seed.db",null,1);
        SQLiteDatabase db=myopenhelper.getReadableDatabase();
        ContentValues values=new ContentValues();
        //list_content={"image","dk","grown","data","fertilizer","manure"};
        Cursor curor_getid=db.query("decision",list_content,null,null,null,null,null,null);
        String curor_id ="0";
        if(curor_getid.getCount()!=0&&curor_getid.moveToLast())curor_id=curor_getid.getString(0);
        else{
            ContentValues values0=new ContentValues();
            values0.put("ID",0);
            values0.put("dk","农科院玉米种植地块");
            values0.put("grown","");
            values0.put("data","");
            values0.put("fertilizer","");
            values0.put("manure","");
            db.insert("decision",null,values0);
            }
        //db.close();
        curor_getid.close();
        int id=1+Integer.valueOf(curor_id);

        values.put("ID",id);
        values.put("dk","农科院玉米种植地块");
        values.put("grown",choose_grown.getText().toString());
        values.put("data",data.getText().toString());
        values.put("fertilizer",fertilizer_value);
        values.put("manure",choose_manure.getText().toString());
        values.put("decisiontype",i);
        db.insert("decision",null,values);
        db.close();

        }
    /**
     * popwindow
     */
    private void showPopupWindow(View view){
        // 一个自定义的布局，作为显示的内容
        View contentView = LayoutInflater.from(this).inflate(
                R.layout.pop_suggest, null);
        // 设置按钮的点击事件
        /**
         * 分享
         */
       TextView share= (TextView) contentView.findViewById(R.id.share_decision);
        share.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent intent = new Intent(Intent.ACTION_SEND);
                intent.setType("text/plain");
                intent.putExtra(Intent.EXTRA_SUBJECT, "方案分享");
                intent.putExtra(Intent.EXTRA_TEXT, "");
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                startActivity(Intent.createChooser(intent, getTitle()));
            }
        });
        /**
         * delet
         */
        TextView delet= (TextView) contentView.findViewById(R.id.delet_decision);
        delet.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {

                    new AlertDialog.Builder(Gsetsuggest_Activity.this).setTitle("系统提示")
                            .setMessage("确认删除此条决策？")
                            .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                                @Override
                                public void onClick(DialogInterface dialog, int which) {

                                        String[] args=new String[]{String.valueOf(operation_id)};
                                        MyopenHelper myopenhelper=new MyopenHelper(Gsetsuggest_Activity.this,"seed.db",null,1);
                                        SQLiteDatabase db=myopenhelper.getReadableDatabase();
                                        db.delete("decision","ID=?",args);
                                        db.close();
                                       // seeddatatolistview();
                                     updatalistview();
                                        Toast.makeText(getApplicationContext(),"已删除",Toast.LENGTH_LONG).show();
                                }
                            }).setNegativeButton("取消",null).create().show();
            }
        });
        /**
         * popwidow
         */
        final PopupWindow popupWindow = new PopupWindow(contentView, WindowManager.LayoutParams.WRAP_CONTENT
                , WindowManager.LayoutParams.WRAP_CONTENT , true);
        popupWindow.setTouchable(true);
        // 如果不设置PopupWindow的背景，无论是点击外部区域还是Back键都无法dismiss弹框
        // 我觉得这里是API的一个bug
        popupWindow.setTouchInterceptor(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {

                return false;
            }
        });
        // 设置好参数之后再show
        popupWindow.setBackgroundDrawable(getResources().getDrawable(
                R.drawable.bt_delet));
        // popupWindow.showAtLocation(view, Gravity.RIGHT,0,0);
        popupWindow.showAsDropDown(view,300,-250);
    }
    /**
     * 更新Listview
     */
    private void updatalistview(){
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();

        MyopenHelper myopenhelper=new MyopenHelper(Gsetsuggest_Activity.this,"seed.db",null,1);
        SQLiteDatabase db=myopenhelper.getReadableDatabase();
        Cursor curor=db.query("decision",list_content,null,null,null,null,null,null);
        if(curor.moveToLast()){
            option.setText("养分决策列表");
            //倒叙重写
        for(curor.moveToLast();!curor.isFirst();curor.moveToPrevious()) {
        Map<String, Object> item1 = new HashMap<String, Object>();
            String id=curor.getString(0);
            String dk=curor.getString(1);
            String grown=curor.getString(2);
            String data=curor.getString(3);
            String fertilizer=curor.getString(4);
            String indexs=curor.getString(6);
            int index=Integer.valueOf(indexs);
            String manure=curor.getString(5);
            item1.put("ID",id);
            item1.put("image",image[index]);
            item1.put("dk", dk);
            item1.put("grown", grown);
            item1.put("data", data);
            item1.put("fertilizer", fertilizer);
            item1.put("manure",manure);
            list.add(item1);}}
        else{
           // TextView option= (TextView) findViewById(R.id.option);
            option.setText("还没有已存在的决策方案");
        }

        curor.close();
        db.close();
        SimpleAdapter adapter = new SimpleAdapter(Gsetsuggest_Activity.this, list, R.layout.suggest_item, new String[]{"ID","image","dk","grown","data","fertilizer","manure"},
                new int[]{R.id.list_id,R.id.photo, R.id.dk, R.id.grown, R.id.list_data,R.id.list_fertilizer,R.id.list_manure});
        //listView = (ListView) findViewById(R.id.seed_data); //(ListView) findViewById(R.id.seed_datagrid);
        listView.setAdapter(adapter);
    }
    /**
     * 从服务器获得决策数据
     */
    private void servlet(final String id){
     final   Handler myHandler=new Handler(){
            @Override
            public void handleMessage(Message msg) {
                String rponse= (String) msg.obj;
            }
        };
        new Thread(new Runnable() {
            @Override
            public void run() {

                GetFromServer getfromserver=new GetFromServer();
                // String result=getfromserver.dopost(jsonstring.replace("\"",""));
                String result=getfromserver.dopost(id,null,getfromserver.seed_url);
                Message msg=new Message();
                msg.obj=result;
                myHandler.sendMessage(msg);
            }
        }).start();
    }
}
